pacman::p_load("ggsignif","margins","ggcorrplot","stargazer","TOSTER")
pacman::p_load("dplyr", "mice", "lme4", "estimatr", "margins", "ggsignif", "data.table", "mefa4", "ggplot2", "xtable", "ggsignif", "ggcorrplot", "stargazer", "TOSTER")
#functions
zero1 <- function(x, minx=NA, maxx=NA){
  res <- NA
  if(is.na(minx)) res <- (x - min(x,na.rm=T))/(max(x,na.rm=T) -min(x,na.rm=T))
  if(!is.na(minx)) res <- (x - minx)/(maxx -minx)
  res
}
#load data
load("DataverseData/Auth_experiment_data.Rdata")


#Figure 6: ideology-----------
a <- (lm((zero1(authoritarianism))~zero1(ideology)+race+education+age+gender,subset(both,politicscondition==1)))
b <- (lm((zero1(authoritarianism))~zero1(ideology)+race+education+age+gender,subset(both,politicscondition==0)))
libconests <- data.frame(rbind(summary(a)$coefficients[2,],summary(b)$coefficients[2,]))
libconests$condition <- c("Politics","Internet")

#Figure 6: pid-----------
a <- (lm((zero1(authoritarianism))~zero1(pid7)+race+education+age+gender,subset(both,politicscondition==1)))
b <- (lm((zero1(authoritarianism))~zero1(pid7)+race+education+age+gender,subset(both,politicscondition==0)))
pidests <- data.frame(rbind(summary(a)$coefficients[2,],summary(b)$coefficients[2,]))
pidests$condition <- c("Politics","Internet")

#Figure 6: symbolic ideology---------------
both$symbolic <- rowMeans(data.frame(both$ideology,both$pid7))

a <- (lm((zero1(authoritarianism))~zero1(symbolic)+race+education+age+gender,subset(both,politicscondition==1)))
b <- (lm((zero1(authoritarianism))~zero1(symbolic)+race+education+age+gender,subset(both,politicscondition==0)))
symbolicests <- data.frame(rbind(summary(a)$coefficients[2,],summary(b)$coefficients[2,]))
symbolicests$condition <- c("Politics","Internet")

#Figure 6: create plot------------
maineffects <- rbind(libconests,pidests,symbolicests)
maineffects$DV <- rep(c("Ideology","Party Identity","Symbolic"),each=2)

a <- (lm((zero1(authoritarianism))~zero1(ideology)*politicscondition+race+education+age+gender+id,subset(both)))
b <- (lm((zero1(authoritarianism))~zero1(pid7)*politicscondition+race+education+age+gender+id,subset(both)))
c <- (lm((zero1(authoritarianism))~zero1(symbolic)*politicscondition+race+education+age+gender+id,subset(both)))


pvalues <- c(summary(a)$coefficients[13,4]/2,summary(b)$coefficients[13,4]/2,summary(c)$coefficients[13,4]/2)
annotation_df <- data.frame(DV=c("Ideology", "Party Identity", "Symbolic"),
                            start=c("Internet"),
                            end=c("Politics"),
                            y=c(.35),
                            label=round(pvalues, digits=2)) #if p-values with stars just p-values

wrapper <- function(x, ...)
{
  paste(strwrap(x, ...), collapse = "\n")
}

#create plot
mm <- ggplot(maineffects,aes(x=condition,y=Estimate))+geom_pointrange(aes(ymin=Estimate-Std..Error*1.64,ymax=Estimate+Std..Error*1.64))+facet_wrap(~DV,nrow=2)+theme_bw(base_size=20)+geom_signif(data=annotation_df, aes(xmin=start, xmax=end, annotations=label, y_position=y),textsize = 3, vjust = -0.2, manual=TRUE)+ylim(0,.40)+ylab("AME")+ylab("Average Marginal Effect")+xlab("")+ theme(plot.title = element_text(size = 10, face = "bold"))
ggsave(mm,file="Results/panel1.pdf",width=6,height=6)

#Figure 7: ideology ----------------
both$ideology3 <- factor(car::recode(both$ideology,"1:3='Liberal';4='Moderate';5:7='Conservative'",as.factor = T),levels=c("Liberal","Moderate","Conservative"))
a <- (lm((zero1(authoritarianism))~politicscondition*ideology3+race+education+age+gender,subset(both)))
marginsideo <- margins(a,data = both,variables = c("politicscondition"),at = list(ideology3=c("Liberal","Moderate","Conservative")))
marginsideo <- summary(marginsideo,level=.9)

#Figure 7: pid ----------------
both$pid <- car::recode(both$pid7,"1:3='Democrat';4='Independent';5:7='Republican'")
a <- (lm((zero1(authoritarianism))~politicscondition*pid+race+education+age+gender,subset(both)))
marginspid <- margins(a,data = both,variables = c("politicscondition"),at = list(pid=c("Democrat","Independent","Republican")))
marginspid <- summary(marginspid,level=.9)
#pidplot <- ggplot(marginspid,aes(x=pid,y=AME))+geom_pointrange(aes(ymin=lower,max=upper))+theme_bw()+geom_hline(yintercept = 0,lty=2)+ylim(-.07,.06)

#Figure 7: symbolic ideology ------------
both$symbolic3 <- factor(as.numeric(gtools::quantcut(both$symbolic,q = seq(0,1,by=.333))),labels=c("Bottom Tertile","Middle Tertile","Upper Tertile"))
a <- (lm((zero1(authoritarianism))~politicscondition*symbolic3+race+education+age+gender,subset(both)))
marginssym <- margins(a,data = both,variables = c("politicscondition"),at = list(symbolic3=c("Bottom Tertile","Middle Tertile","Upper Tertile")),level=.9)
marginssym <- summary(marginssym,level=.9)

#Figure 7: create plot-----------
colnames(marginssym)[2] ="id"
colnames(marginsideo)[2] ="id"
colnames(marginspid)[2] ="id"
forplot <- data.frame(rbind(marginsideo,marginspid,marginssym))
forplot$level <- c(levels(both$ideology3),levels(as.factor(both$pid)),levels(both$symbolic3))
forplot$dv <- rep(c("Ideology","Party Identity","Symbolic"),each=3)
symplot <- ggplot(forplot,aes(x=id,y=AME))+geom_pointrange(aes(ymin=lower,max=upper))+theme_bw(base_size=10)+geom_hline(yintercept = 0,lty=2)+ylim(-.07,.07)+facet_wrap(dv~.,scales="free_x",nrow=3)+xlab("")+ylab("Average Marginal Effect")+theme(axis.text.x = element_text(face = "bold", size = 10, angle = 45, hjust = 1))+ theme(plot.title = element_text(size = 10, face = "bold"))
ggsave(symplot,file="Results/panel2.pdf",width=6,height=6)


#SI 6.3 descriptive statistics----------
select<-c("age","gender","education","race")
descr<-both[select]

summary(descr$age)
sd(descr$age, na.rm=T)
table(descr$gender)
(752*100)/(781+752+9)
(781*100)/(781+752+9)
(9*100)/(781+752+9)

table(descr$education)
(918*100)/(918+382+242)

table(descr$race)
(1042*100)/(1042+136+149+216)

#SI 6.3 correlation between variables----------------
pers_cor <- (dplyr::select(both,pid7, ideology,symbolic, authoritarianism))
pers_cor <- pers_cor
pers_cor <- cor(pers_cor,use="pairwise.complete.obs")
rownames(pers_cor) <- c("Party Identity","Ideology","Symbolic","Authoritarianism")
a<-ggcorrplot(pers_cor, type="lower", show.diag = TRUE, lab=TRUE, lab_size = 4 , title="A. Correlation between items")
ggsave(a,file="Results/experiment_cors.png",width=8,height=8)

#SI 6.4 results belonging to Figure 6 and 7------------
a <- lm((zero1(authoritarianism))~zero1(ideology)*politicscondition+race+education+age+gender,both)
b <- lm((zero1(authoritarianism))~zero1(pid7)*politicscondition+race+education+age+gender,both)
c <- lm((zero1(authoritarianism))~zero1(symbolic)*politicscondition+race+education+age+gender,both)

stargazer(a,b,c, column.separate = c(1,1,1,1),dep.var.caption = "",dep.var.labels = "Authoritarianism", covariate.labels = c("Ideology","Party ID", "Symbolic","Politics Condition","Race: Hispanic", "Race: Other", "Race: White", "Education: High school or less", "Education: Some college","Gender: Male", "Gender: Other", "Age","Ideology x Politics Condition","PID x Politics Condition","Symbolic x Politics Condition","Constant" ), title="Results belonging to Figure 6 in the main text", no.space = TRUE, align=TRUE, model.numbers = FALSE, omit.stat=c("LL","ser","f", "adj.rsq"), star.char = c("+", "*"), star.cutoffs = c(.1, 0.05), notes = c("+ p<.1; * p<0.05)"), notes.append = F, out="Results/authexperimentmain.tex", label="tab:authexpt", digits=2,p = list(summary(a)$coefficients[,4]/2,summary(b)$coefficients[,4]/2,summary(c)$coefficients[,4]/2))

both$ideology3 <- relevel(both$ideology3,ref="Conservative")
both$pid <- relevel(as.factor(both$pid),ref="Republican")
both$symbolic3 <- relevel(as.factor(both$symbolic3),ref="Upper Tertile")

a <- lm((zero1(authoritarianism))~(ideology3)*politicscondition+race+education+age+gender,both)
b <- lm((zero1(authoritarianism))~(pid)*politicscondition+race+education+age+gender,both)
c <- lm((zero1(authoritarianism))~(symbolic3)*politicscondition+race+education+age+gender,both)

stargazer(a,b,c, column.separate = c(1,1,1,1),dep.var.caption = "",dep.var.labels = "Authoritarianism", covariate.labels = c("Liberal","Moderate","Democrat","Independent" ,"Symbolic: Lower Tertile","Symbolic: Middle Tertile","Politics Condition","Race: Hispanic", "Race: Other", "Race: White", "Education: High school or less", "Education: Some college","Gender: Male", "Gender: Other", "Age","Liberal x Politics Condition","Moderate x Politics Condition","Democrat x Politics Condition","Independent x Politics Condition","Symbolic Lower Tertile x Politics Condition","Symbolic Middle Tertile x Politics Condition","Constant" ), title="Results belonging to Figure 7 in the main text", no.space = TRUE, align=TRUE, model.numbers = FALSE, omit.stat=c("LL","ser","f", "adj.rsq"), star.char = c("+", "*"), star.cutoffs = c(.1, 0.05), notes = c("+ p<.1; * p<0.05)"), notes.append = F, out="Results/authexperimentmain3.tex", label="tab:authexpt", digits=2,p = list(summary(a)$coefficients[,4]/2,summary(b)$coefficients[,4]/2,summary(c)$coefficients[,4]/2))

#SI 6.5 results without B5 experiment ----------
#ideology
a <- (lm((zero1(authoritarianism))~zero1(ideology)+race+education+age+gender,subset(both,politicscondition==1 & id==1)))
b <- (lm((zero1(authoritarianism))~zero1(ideology)+race+education+age+gender +id,subset(both,politicscondition==0& id==1)))
libconests <- data.frame(rbind(summary(a)$coefficients[2,],summary(b)$coefficients[2,]))
libconests$condition <- c("Politics","Internet")

#pid
a <- (lm((zero1(authoritarianism))~zero1(pid7)+race+education+age+gender +id,subset(both,politicscondition==1& id==1)))
b <- (lm((zero1(authoritarianism))~zero1(pid7)+race+education+age+gender +id,subset(both,politicscondition==0& id==1)))
pidests <- data.frame(rbind(summary(a)$coefficients[2,],summary(b)$coefficients[2,]))
pidests$condition <- c("Politics","Internet")

#symbolic
a <- (lm((zero1(authoritarianism))~zero1(symbolic)+race+education+age+gender +id,subset(both,politicscondition==1& id==1)))
b <- (lm((zero1(authoritarianism))~zero1(symbolic)+race+education+age+gender +id,subset(both,politicscondition==0& id==1)))
symbolicests <- data.frame(rbind(summary(a)$coefficients[2,],summary(b)$coefficients[2,]))
symbolicests$condition <- c("Politics","Internet")

maineffects <- rbind(libconests,pidests,symbolicests)
maineffects$DV <- rep(c("Ideology","Party Identity","Symbolic"),each=2)
a <- (lm((zero1(authoritarianism))~zero1(ideology)*politicscondition+race+education+age+gender,subset(both, id==1)))
b <- (lm((zero1(authoritarianism))~zero1(pid7)*politicscondition+race+education+age+gender,subset(both, id==1)))
c <- (lm((zero1(authoritarianism))~zero1(symbolic)*politicscondition+race+education+age+gender,subset(both, id==1)))
pvalues <- c(summary(a)$coefficients[12,4]/2,summary(b)$coefficients[12,4]/2,summary(c)$coefficients[12,4]/2)
annotation_df <- data.frame(DV=c("Ideology", "Party Identity", "Symbolic"),
                            start=c("Internet"),
                            end=c("Politics"),
                            y=c(.35),
                            label=round(pvalues, digits=3)) #if p-values with stars just p-values
wrapper <- function(x, ...)
{
  paste(strwrap(x, ...), collapse = "\n")
}

mm <- ggplot(maineffects,aes(x=condition,y=Estimate))+geom_pointrange(aes(ymin=Estimate-Std..Error*1.64,ymax=Estimate+Std..Error*1.64))+facet_wrap(~DV,nrow=3)+theme_bw(base_size=20)+geom_signif(data=annotation_df, aes(xmin=start, xmax=end, annotations=label, y_position=y),textsize = 3, vjust = -0.2, manual=TRUE)+ylim(0,.40)+ylab("AME")+ggtitle(wrapper("Association between Political Attitude and Authoritarianism by Condition",width=50))+ylab("Average Marginal Effect")+xlab("")+ theme(plot.title = element_text(size = 10, face = "bold"))
ggsave(plot = mm,"Results/effectswithoutwave1.pdf")

#SI 6.6 randomization check ---------
#PID
a <- mean((zero1(both$pid7))[both$politicscondition==0],na.rm=T)
a1 <- sd((zero1(both$pid7))[both$politicscondition==0],na.rm=T)
b <- mean((zero1(both$pid7))[both$politicscondition==1],na.rm=T)
b1 <- sd((zero1(both$pid7))[both$politicscondition==1],na.rm=T)
n1 <- table(na.omit(both$politicscondition))[1]
n2 <- table(na.omit(both$politicscondition))[2]
TOSTtwo(m1=a, m2=b, sd1=a1*2, sd2=b1*2, n1, n2, low_eqbound_d=-0.2, high_eqbound_d=0.2, alpha = .05)

#Ideology
a <- mean((zero1(both$ideology))[both$politicscondition==0],na.rm=T)
a1 <- sd((zero1(both$ideology))[both$politicscondition==0],na.rm=T)
b <- mean((zero1(both$ideology))[both$politicscondition==1],na.rm=T)
b1 <- sd((zero1(both$ideology))[both$politicscondition==1],na.rm=T)
n1 <- table(na.omit(both$politicscondition))[1]
n2 <- table(na.omit(both$politicscondition))[2]
TOSTtwo(m1=a, m2=b, sd1=a1*2, sd2=b1*2, n1, n2, low_eqbound_d=-0.2, high_eqbound_d=0.2, alpha = .05)

#symbolic
a <- mean((zero1(both$symbolic))[both$politicscondition==0],na.rm=T)
a1 <- sd((zero1(both$symbolic))[both$politicscondition==0],na.rm=T)
b <- mean((zero1(both$symbolic))[both$politicscondition==1],na.rm=T)
b1 <- sd((zero1(both$symbolic))[both$politicscondition==1],na.rm=T)
n1 <- table(na.omit(both$politicscondition))[1]
n2 <- table(na.omit(both$politicscondition))[2]
TOSTtwo(m1=a, m2=b, sd1=a1*2, sd2=b1*2, n1, n2, low_eqbound_d=-0.2, high_eqbound_d=0.2, alpha = .05)

#SI 9.1: conditional effects on age-------
cond_age<-list()
cond_age[[1]] <- lm((zero1(authoritarianism))~zero1(ideology)*politicscondition*age+race+education+gender,both)
cond_age[[2]] <- lm((zero1(authoritarianism))~zero1(pid7)*politicscondition*age+race+education+gender,both)
cond_age[[3]] <- lm((zero1(authoritarianism))~zero1(symbolic)*politicscondition*age+race+education+gender,both)

#SI 9.2: conditional effects on education-------------
both$edu01<-ifelse(both$education=="College+", 1,0)
cond_edu<-list()
cond_edu[[1]] <- lm((zero1(authoritarianism))~zero1(ideology)*politicscondition*edu01+ age+race+gender,both)
cond_edu[[2]] <- lm((zero1(authoritarianism))~zero1(pid7)*politicscondition*edu01+ age+race+gender,both)
cond_edu[[3]] <- lm((zero1(authoritarianism))~zero1(symbolic)*politicscondition*edu01+ age+race+gender,both)

